package com.chatplus.application.common.util;

import cn.hutool.extra.spring.SpringUtil;
import org.redisson.api.RMap;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.Collections;
import java.util.Objects;
import java.util.Set;

/**
 * 缓存操作工具类 {@link }
 */
@SuppressWarnings(value = {"unchecked"})
public class CacheGroupUtils {

    private CacheGroupUtils() {
    }
    private static final CacheManager CACHE_MANAGER = SpringUtil.getBean(CacheManager.class);

    /**
     * 获取缓存组内所有的KEY
     *
     * @param cacheNames 缓存组名称
     */
    public static Set<Object> keys(String cacheNames) {
        Cache cache = CACHE_MANAGER.getCache(cacheNames);
        if (cache == null) {
            return Collections.emptySet();
        }
        RMap<Object, Object> rmap = (RMap<Object, Object>) cache.getNativeCache();
        return rmap.keySet();
    }

    /**
     * 获取缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     */
    public static <T> T get(String cacheNames, Object key) {
        if (CACHE_MANAGER.getCache(cacheNames) == null) {
            return null;
        }
        Cache.ValueWrapper wrapper = Objects.requireNonNull(CACHE_MANAGER.getCache(cacheNames)).get(key);
        return wrapper != null ? (T) wrapper.get() : null;
    }

    /**
     * 保存缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     * @param value      缓存值
     */
    public static void put(String cacheNames, Object key, Object value) {
        Cache cache = CACHE_MANAGER.getCache(cacheNames);
        if (cache == null) {
            return;
        }
        cache.put(key, value);
    }

    /**
     * 删除缓存值
     *
     * @param cacheNames 缓存组名称
     * @param key        缓存key
     */
    public static void evict(String cacheNames, Object key) {
        Cache cache = CACHE_MANAGER.getCache(cacheNames);
        if (cache == null) {
            return;
        }
        cache.evict(key);
    }

    /**
     * 清空缓存值
     *
     * @param cacheNames 缓存组名称
     */
    public static void clear(String cacheNames) {
        Cache cache = CACHE_MANAGER.getCache(cacheNames);
        if (cache == null) {
            return;
        }
        cache.clear();
    }

}
